<template>
    <div class="main-content">
        <echartsLayout :formState='formState' :dataListState='dataListState' :eCharts1State='eCharts1State' :eCharts2State='eCharts2State' 
        :eCharts3State='eCharts3State' :chartsListState='chartsListState' :tableState='tableState'>
            <div slot="form">
                <el-form :model="query" ref="query" label-width="70px" label-position="right">
                    <el-row :gutter="41">
                         <el-col :span="7">
                            <el-form-item label="省份" prop="provinceId">
                                <province v-model="query.provinceId" :name.sync="query.provinceName"></province>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="市区" prop="cityId">
                                <city v-model="query.cityId" :province="query.provinceId" :name.sync="query.cityName"></city>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="区县" prop="areaId">
                                <region v-model="query.areaId" :city="query.cityId" :name.sync="query.areaName"></region>
                            </el-form-item>
                        </el-col>
                    </el-row> 
                    <el-row :gutter="41">
                        <el-col :span="7">
                            <el-form-item label="服务类型" prop="serviceType">
                                <el-select v-model="query.serviceType" placeholder="请选择" style="width:100%">
                                    <el-option v-for="item in serviceTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="日期">
                                <el-row>
                                    <el-col :span="11">
                                        <el-date-picker v-model="query.startDate" :clearable="false" :editable="false" type="date" placeholder="选择开始日期" :picker-options="pickerOptions1" @change="startDateChange" style="width:100%"></el-date-picker>
                                    </el-col>
                                    <el-col :span="2" align="center">-</el-col>
                                    <el-col :span="11">
                                        <el-date-picker v-model="query.endDate" :clearable="false" :editable="false" type="date" placeholder="选择结束日期" :picker-options="pickerOptions2" @change="endDateChange" style="width:100%"></el-date-picker>
                                    </el-col>
                                </el-row>  
                            </el-form-item>
                        </el-col>
                        <el-col :span="3" :offset="7">
                            <div class="top-line">
                                <el-button type="primary" class="btn-common" @click="onSubmit">查询</el-button>
                            </div>
                        </el-col>
                    </el-row> 
                </el-form>
            </div> 
            <div slot="eCharts1" >
                <div class="charts-title">服务销量统计</div>
                <div class="charts-display" v-loading='chartLoading'>
                    <trendChart width='100%' height='100%' id="barChart1" :option='barChart1Option'></trendChart>
                </div>
            </div>
            <div slot="table" >
                <div class="table-title">
                    <exportExcel :jsonStr='jsonStr'></exportExcel>
                </div> 
                <el-table :data="tableData" border v-loading="loading" style="width: 100%" :default-sort = "{prop: 'login', order: 'descending'}" @sort-change='sortChange'>
                    <el-table-column label="服务类型" align="center">
                        <template scope="scope">
                            <span>{{scope.row.paymentType | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="收取金额" align="center" sortable='custom' prop="$AppViewScreen.unique">
                        <template scope="scope">
                            <span>{{scope.row.name0 | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="收取卡券金额" align="center" sortable='custom' prop="$AppViewScreen.unique">
                        <template scope="scope">
                            <span>{{scope.row.name1 | isNull}}</span>
                        </template>
                    </el-table-column>
    
                    <el-table-column label="销售量" align="center" sortable='custom' prop="$AppViewScreen.unique">
                        <template scope="scope">
                            <span>{{scope.row.name2 | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="区域" align="center">
                        <template scope="scope">
                            <span>{{scope.row['user.area'] | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="城市" align="center">
                        <template scope="scope">
                            <span>{{scope.row['user.city'] | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="省份" align="center">
                        <template scope="scope">
                            <span>{{scope.row['user.province'] | isNull}}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-container">
                    <el-pagination
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageQuery.total"
                        :current-page.sync="pageQuery.currentpage"
                        :page-sizes="config.pageSizes"
                        :page-size="config.pageSize"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </echartsLayout>
    </div>
</template>

<script>
    import moment from 'moment';
    import province from 'components/CascadeRegion/province';
    import city from 'components/CascadeRegion/city';
    import region from 'components/CascadeRegion/region';
    import trendChart from 'components/Charts/trendChart';
    import echartsLayout from 'components/TableLayout/echartsLayout'; 
    import exportExcel from 'components/ExportExcel';  
    import { mapState, mapActions } from 'vuex';
    export default{
        components: { echartsLayout, province, city, region, trendChart, exportExcel },
        data() {
            return {
                chartLoading: false,
                loading: false,
                formState: false,
                dataListState: true,
                eCharts1State: false,
                eCharts2State: true,
                eCharts3State: true,
                chartsListState: true,
                tableState: false,
                serviceTypeList: [{  
                    value: '',
                    label: '请选择'
                }, {
                    value: 'e直播',
                    label: 'e直播'
                }, {
                    value: '空中课堂',
                    label: '空中课堂'
                // }, {
                //     value: '2',
                //     label: '刷脸考勤'
                // }, {
                //     value: '3',
                //     label: 'RFID'
                }],
                query: {
                    provinceId: '',
                    cityId: '',
                    areaId: '',
                    provinceName: '',
                    cityName: '',
                    areaName: '',
                    serviceType: '',
                    startDate: new Date(),
                    endDate: new Date(),
                    sortBy: 'name0',
                    flag: true
                },
                tableData: [],
                pageQuery: {
                    currentpage: 1,
                    total: 0
                },
                pickerOptions1: null,
                pickerOptions2: null,
                barChart1Option: null,
                measuresList: [],
                filterList: null,
                jsonStr: null
            }
        },
        computed: {
            ...mapState({
                config: state => state.config.table
            })
        },
        created() {
            this.queryData();
            this.getTableList();
        },
        methods: {
            ...mapActions(['ChangePageSize']),
            handleSizeChange(val) {
                this.pageQuery.currentpage = 1;
                this.ChangePageSize(val);
                this.getTableList();
            },
            handleCurrentChange(val) {
                this.pageQuery.currentpage = val;
                this.getTableList();
            },
            // getProvinceName(provinceName) {
            //     this.query.provinceName = provinceName;
            // },
            // getCityName(cityName) {
            //     this.query.cityName = cityName;
            // },
            // getAreaName(areaName) {
            //     this.query.areaName = areaName;
            // },
            onSubmit() {
                let conditionsList = [];
                if (this.query.provinceName) {
                    conditionsList.push({'field': 'user.province', 'function': 'equal', 'params': [this.query.provinceName]});
                }
                if (this.query.cityName) {
                    conditionsList.push({'field': 'user.city', 'function': 'equal', 'params': [this.query.cityName]});
                }
                if (this.query.areaName) {
                    conditionsList.push({'field': 'user.area', 'function': 'equal', 'params': [this.query.areaName]});
                }

                this.filterList = {};
                if (conditionsList.length == 1) {
                    this.filterList = {'conditions': conditionsList};
                } else if (conditionsList.length > 1) {
                    this.filterList = {'relation': 'and', 'conditions': conditionsList};
                } else {
                    this.filterList = {};
                }

                // this.measuresList = [
                //         {'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.actualPayment'}, 
                //         {'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.couponValue'}, 
                //         {'event_name': 'elivePaymentSucceed', 'aggregator': 'general'}, 
                //         {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.actualPayment'}, 
                //         {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.couponValue'}, 
                //         {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'general'}
                // ];

                // if (this.query.serviceType == 'e直播') {
                //     this.measuresList.push({'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.actualPayment'});
                //     this.measuresList.push({'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.couponValue'});
                //     this.measuresList.push({'event_name': 'elivePaymentSucceed', 'aggregator': 'general'});
                // } else if (this.query.serviceType == '空中课堂') {
                //     this.measuresList.push({'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.actualPayment'});
                //     this.measuresList.push({'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.couponValue'});
                //     this.measuresList.push({'event_name': 'airCoursePaymentSucceed', 'aggregator': 'general'});
                // }

                this.pageQuery.currentpage = 1;
                this.queryData();
                this.getTableList();
            },

            // 服务统计图
            queryData() {
                let startDate = this.query.startDate==''?'':moment(this.query.startDate).format('YYYY-MM-DD'); 
                let endDate = this.query.endDate==''?'':moment(this.query.endDate).format('YYYY-MM-DD'); 
               
                let query = {
                    'measures': 
                    [
                        {'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.actualPayment'}, 
                        {'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.couponValue'}, 
                        {'event_name': 'elivePaymentSucceed', 'aggregator': 'general'}, 
                        {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.actualPayment'}, 
                        {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.couponValue'}, 
                        {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'general'}
                    ], 
                    'unit': 'day', 
                    'filter': this.filterList,
                    'sampling_factor': 64, 
                    'from_date': startDate, 'to_date': endDate, 
                    'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1517041198133};
                let inforSent = {
                    query_id: 41,
                    real_time: false,
                    type: 'bar',
                    formInline: 'day',
                    query
                };
                this.chartLoading = true;
                this.$store.dispatch('getQuery', inforSent).then(({data}) => {
                    this.chartLoading = false;
                    let rows = data.detail_result.rows[0].values[0];
                    let bar1 = [];
                    let bar2 = [];
                    let bar3 = [];
                    bar1 = rows.filter((item, i) => i % 3 == 0);
                    bar2 = rows.filter((item, i) => i % 3 == 1);
                    bar3 = rows.filter((item, i) => i % 3 == 2);
                    this.barChart1Option = {
                        color: ['#2EC7C9', '#B6A2DE', '#5AB1EF', '#FFB980'],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                                type: 'line'        // 默认为直线，可选为：'line' | 'shadow'
                            }
                        },
                        legend: {
                            data: ['收取金额', '卡券金额', '销售量'] // , '入校量'
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: 'category',
                                data: ['e直播', '空中课堂'], // '刷脸考勤', 'RFID', 
                                axisTick: {
                                    alignWithLabel: true
                                }
                            }
                        ],
                        yAxis: [
                            {
                                type: 'value'
                            }
                        ],
                        series: [
                            {
                                name: '收取金额',
                                type: 'bar',
                                data: bar1
                            },
                            {
                                name: '卡券金额',
                                type: 'bar',
                                data: bar2
                            },
                            {
                                name: '销售量',
                                type: 'bar',
                                data: bar3
                            }
                            // {
                            //     name: '入校量',
                            //     type: 'bar',
                            //     data: [101, 522, 100, 334]
                            // }
                        ]
                    };
                }).catch(() => {
                    this.chartLoading = false;
                });
            },

            // 服务销量列表
            getTableList() {
                let startDate = this.query.startDate==''?'':moment(this.query.startDate).format('YYYY-MM-DD'); 
                let endDate = this.query.endDate==''?'':moment(this.query.endDate).format('YYYY-MM-DD'); 
              
                let query = {
                    'paymentType': this.query.serviceType, 
                    'order_field': '', 
                    'order_desc': true, 
                    'measures': [{'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.actualPayment'}, {'event_name': 'elivePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.elivePaymentSucceed.couponValue'}, {'event_name': 'elivePaymentSucceed', 'aggregator': 'general'}, {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.actualPayment'}, {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'SUM', 'field': 'event.airCoursePaymentSucceed.couponValue'}, {'event_name': 'airCoursePaymentSucceed', 'aggregator': 'general'}], 'unit': 'day', 
                    'filter': this.filterList, 
                    'by_fields': ['user.province', 'user.city', 'user.area'], 'sampling_factor': 64, 
                    'from_date': startDate, 'to_date': endDate, 
                    'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1517041281401};
                let inforSent = {
                    query_id: 42,
                    real_time: false,
                    showList: true,
                    page_index: this.pageQuery.currentpage,
                    page_size: this.config.pageSize,
                    query 
                };

                this.jsonStr = {
                    'query_id': 42, 
                    'show_list': true, 
                    'real_time': false,
                    'type': 'event',
                    'file_name': '服务销量列表', 
                    'field_names': [['服务类型', 'paymentType'], ['收取金额', 'name0'], ['收取卡券金额', 'name1'], ['销售量', 'name2'], ['区域', 'user.area'], ['城市', 'user.city'], ['省份', 'user.province']],
                    query
                };
                this.loading = true;
                this.$store.dispatch('getQuery', inforSent).then((response) => {
                    this.loading = false;
                    this.tableData = [];
                    if (response.data) {
                        this.tableData = response.data.rows;
                        this.pageQuery.total = response.data.total_rows;
                    }
                }).catch(() => {
                    this.loading = false;
                    this.tableData = [];
                });
            },
            startDateChange(date) {
                this.pickerOptions2 = {
                    disabledDate(time) {
                        return (time.getTime() < new Date(date).getTime() - 864e5);
                    }
                }
            },
            endDateChange(date) {
                this.pickerOptions1 = {
                    disabledDate(time) {
                        return (time.getTime() > new Date(date).getTime());
                    }
                } 
            },
            sortChange({ column, prop, order }) {
                this.query.sortBy = prop?prop:'name0';
                this.query.flag = order=='ascending'?false:true;
                this.getTableList();
            }
        }
    }
</script>
<style lang="scss" scoped>
    .main-content {
        position: relative;
        $bgcolor: #fff;
    }
</style>                     